<template>
  <div class="pagination">
    <button @click='changeNum(pageNo-1)' :disabled='pageNo===1'>上一页</button>
    <button v-show='startAndend.start>1' @click='changeNum(1)'>1</button>
    <span v-show='startAndend.start>2'>...</span>
    <button :class='{"active":pageNo===startAndend.start+index}' v-for='(_,index) in (startAndend.end - startAndend.start + 1)' :key='_' @click='changeNum(startAndend.start+index)'>{{startAndend.start+index}}</button>
    <button v-show='startAndend.end < totalPage - 1'>···</button>
    <button v-show='startAndend.end < totalPage' @click='changeNum(totalPage)'>{{totalPage}}</button>
    <button @click='changeNum(pageNo+1)' :disabled='pageNo===totalPage'>下一页</button>

    <span>共 {{total}} 条</span>
  </div>
</template>

<script>
export default {
  name: 'Pagination',
  props: ['pageNo', 'pageSize', 'total', 'continues'],
  computed: {
    // 计算总页码
    totalPage() {
      const { pageSize, total } = this;
      return Math.ceil(total / pageSize); // 向上取整
    },
    // 计算起始和结束页码
    startAndend() {
      const { pageNo, continues, totalPage, pageSize } = this;
      let start, end;
      // 特殊情况1：如果连贯页码 【大于】 总页码！！！！！！
      if (continues > totalPage) {
        start = 1; // 起始页从1开始
        end = totalPage; // 结束页就是总页码
      } else {
        start = pageNo - parseInt(continues / 2);
        end = pageNo + parseInt(continues / 2);
        // 特殊情况2：起始页码小于1！！！！！！
        if (start < 1) {
          start = 1; // 起始页码不能小于1
          end = continues;
        }
        // 特殊情况3：结束页码 大于 总页码
        if (end > totalPage) {
          start = totalPage - continues + 1;
          end = totalPage;
        }
      }

      return { start, end };
    }
  },
  methods: {
    changeNum(pageNum) {
      this.$emit('get-pageNo', pageNum);
    }
  }
};
</script>

<style lang="less" scoped>
.pagination {
  text-align: center;
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #c81623;
      color: #fff;
    }
  }
  span {
    display: inline-block;
    line-height: 28px;
    font-size: 14px;
    color: gray;
    vertical-align: middle;
  }
}
</style>